package com.stedu.service.impl;

import com.stedu.bean.Repairer;
import com.stedu.mapper.RepairTaskMapper;
import com.stedu.mapper.RepairerMapper;
import com.stedu.service.RepairerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RepairerServiceImpl implements RepairerService {

    @Autowired
    private RepairerMapper repairerMapper;
    @Autowired
    private RepairTaskMapper repairTaskMapper;

    @Override
    public Repairer selectByRid(Integer rid) {
        Repairer repairer = repairerMapper.selectByRid(rid);
        return repairer;
    }

    @Override
    public List<Repairer> selectByRname(String rname) {
        return repairerMapper.selectByrname(rname);
    }

    @Override
    public boolean insert(Repairer r) {
        r.setEstate(1);
        return repairerMapper.insert(r) == 1;
    }

    // 检查是否存在关联的任务
    private boolean hasRelatedTasks(Integer rid) {
        List<Integer> tidList = repairTaskMapper.selectTidByRid(rid);
        // 假设只有当所有关联任务的状态都为已完成（假设状态值为 2 表示已完成）时才能删除维修人员信息
        for (Integer tid : tidList) {
            Integer rstate = repairTaskMapper.getTaskState(tid);
            if (rstate!= 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer rid) {
        if (!hasRelatedTasks(rid)) {
            return repairerMapper.delete(rid) == 1;
        } else {
            return false;
        }
    }

    @Override
    public boolean update(Repairer r) {
        System.out.println(repairerMapper.update(r));
        return repairerMapper.update(r) == 1;
    }

    @Override
    public List<Repairer> selectAll() {
        List<Repairer> repairerList = repairerMapper.selectAll();
        repairerList.stream().forEach(System.out::println);
        return repairerList;
    }

    @Override
    public Repairer selectByRusername(String rusername) {
        Repairer repairer = repairerMapper.selectByRusername(rusername);
        return repairer;
    }

}